﻿using System;
using System.Collections.Generic;

namespace TTGStudios.NotificationCenterNET
{
    public class NotificationCenter<ID_TYPE>
    {
        public delegate void MessageHandler(ID_TYPE message, object sender, object args);

        private static NotificationCenter<ID_TYPE> singleton;
        public static NotificationCenter<ID_TYPE> Instance
        {
            get
            {
                if (singleton == null)
                {
                    singleton = new NotificationCenter<ID_TYPE>();
                }

                return singleton;
            }
        }

        private NotificationCenter()
        {
            events = new Dictionary<ID_TYPE, MessageHandler>();
        }

        private Dictionary<ID_TYPE, MessageHandler> events;

        public void SubscribeToMessage(ID_TYPE messageID, MessageHandler handler)
        {
            if (events.ContainsKey(messageID))
            {
                events[messageID] = events[messageID] + handler;
            }
            else
            {
                events[messageID] = handler;
            }
        }

        public void UnsubscribeFromMessage(ID_TYPE messageID, MessageHandler handler)
        {
            if (events.ContainsKey(messageID))
            {
                events[messageID] = events[messageID] - handler;
                if (events[messageID] == null)
                {
                    events.Remove(messageID);
                }
            }
        }

        public void SendMessage(ID_TYPE messageID, object sender, object args)
        {
            if (events.ContainsKey(messageID))
            {
                events[messageID](messageID, sender, args);
            }
        }
    }
}
